﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.IO;

namespace MelectricComponents
{
    public class XMLUtility
    {
        /// <summary>
        /// Saves a childnode to the parentnode with the supplied attributes
        /// </summary>
        /// <param name="ParentNodeName"></param>
        /// <param name="ChildNodeName"></param>
        /// <param name="ChildNodeAttributes"></param>
        /// <returns></returns>
        public XmlNode SaveXML(string ParentNodeName, string ChildNodeName, Dictionary<string, string> ChildNodeAttributes)
        {
            string sFileName = "";
            StreamReader sr = new StreamReader("debug.txt");
            if (sr.ReadLine() == "true")
            {
                sFileName = "debug.xml";
            }
            else
            {
                sFileName = "MobileLife.xml";
            }
            sr.Close();
            XmlDocument xmlDoc = new XmlDocument();
            XmlNode oRootNode;
            XmlNode oWeightsNode;
            try
            {
                xmlDoc.Load(sFileName);
                oRootNode = xmlDoc.DocumentElement;
            }
            catch (Exception)
            {
                oRootNode = xmlDoc.CreateNode(XmlNodeType.Element, "MobileLife", "");
                xmlDoc.AppendChild(oRootNode);
            }
            XmlNode WeightNode = oRootNode.SelectSingleNode("//" + ParentNodeName);
            if (WeightNode == null)
            {
                oWeightsNode = xmlDoc.CreateNode(XmlNodeType.Element, ParentNodeName, "");
                oRootNode.AppendChild(oWeightsNode);
                WeightNode = oRootNode.SelectSingleNode("//" + ParentNodeName);
            }
            XmlNode ReadingNode = xmlDoc.CreateNode(XmlNodeType.Element, ChildNodeName, "");
            foreach (KeyValuePair<string, string> Attribute in ChildNodeAttributes)
            {

                if (ReadingNode.Attributes[Attribute.Key] == null)
                {
                    XmlAttribute xmlatt = xmlDoc.CreateAttribute(Attribute.Key);
                    ReadingNode.Attributes.Append(xmlatt);
                }
                ReadingNode.Attributes[Attribute.Key].Value = Attribute.Value;


            }

            WeightNode.AppendChild(ReadingNode);
            xmlDoc.Save(sFileName);
            return WeightNode;
        }


    }
}
